package com.iflytek.ci.cpms.controller;

import com.iflytek.ci.common.support.DateEditor;
import com.iflytek.ci.cpms.domain.Milestone;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.cpms.dto.MilestoneReport;
import com.iflytek.ci.cpms.service.MilestoneReprterService;
import com.iflytek.ci.cpms.service.MilestoneService;
import com.iflytek.ci.cpms.service.ProjectService;
import com.iflytek.ci.cpms.service.impl.MilestoneReprterServiceImpl;
import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.main.dto.Prior;
import com.iflytek.framework.web.messages.AjaxMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 里程碑向导控制器
 * </p>
 *
 * @author xzyan
 * @version 1.0 2013-1-14 11:34 AM
 * @since JDK 1.5
 */


@Controller
@RequestMapping("/project/milestone/wizard/**")
////可以使用SessionStatus对象进行删除。
@SessionAttributes(value = {"milestoneReport"})
public class MilestoneWizardFormController extends BaseController{

    /**	序列号*/
	private static final long serialVersionUID = -801450011104073372L;

	/**项目服务*/
    @Autowired
    private ProjectService projectService;

    @Autowired 
    private MilestoneReprterService milestoneReprterService;
    /**里程碑服务*/
    @Autowired
    private MilestoneService milestoneService;

    protected static Logger logger =Logger.getLogger(MilestoneWizardFormController.class);

    /**
     * 对Date类型的日期格式与字符串格式进行转换
     * @param request
     * @param binder
     * @throws Exception
     */
    @InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        // 对于需要转换为Date类型的属性，使用DateEditor进行处理
        binder.registerCustomEditor(Date.class, new DateEditor(null));
    }
    /**
     * 用于加载第一个表单视图，并初始化里程碑对象
     *
     * @param model ui model
     * @return 第一个表单页面视图
     */
    @RequestMapping(value = "setup/{milestone_id}",method = RequestMethod.GET)
    public String setupForm(
            @PathVariable(value = "milestone_id") int milestoneId,
            Model model) {
        //初始化  里程碑报告信息
        Milestone milestone = milestoneService.get_milestone_id(milestoneId);
        MilestoneReport milestoneReport = new MilestoneReport();
        milestoneReport.setStartTime(milestone.getCreateTime());
        milestoneReport.setDueTime(milestone.getDuetime());

        Project project = projectService.fromId( milestone.getProject());
        model.addAttribute("milestoneReport",milestoneReport);
        model.addAttribute("project",project);
        model.addAttribute("milestone",milestone);
        return "project/milestone/WizardForm/step1";
    }

    /**
     * 根据svn目录得到build_note号
     *
     * @return  build_note号
     */
    @ResponseBody
    @RequestMapping(value = "get_build_note",method = RequestMethod.POST)
    public AjaxMessage getBuildNote(int milestone_id){
        Milestone milestone = milestoneService.get_milestone_id(milestone_id);
        Project project = projectService.fromId(milestone.getProject());
        String buildNote = new String();
        try{
        buildNote = milestoneReprterService.setBuildNote(milestone,project);
        }catch (Exception e){
           logger.info("get build note failed");
            return ajax_error("获得构建号失败");
        }
        return ajax_info(buildNote);
    }


	/**
	 * 里程碑构建向导 控制入口
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param milestoneId
	 *            项目缩写
	 * @param cancel
	 *            里程碑取消操作
	 * @param finish
	 *            完成操作
	 * @param milestoneReport
	 *            里程碑报告dto对象
	 * @param result
	 *            数据绑定结果
	 * @param status
	 *            session状态
	 * @param currentPage
	 *            当前页面
	 * @param model
	 *            ui model
	 * @return 视图
	 */
	@RequestMapping(value = "wizard_form/{milestone_id}", method = RequestMethod.POST)
	public String submitForm(HttpServletRequest request,
			@PathVariable(value = "milestone_id") int milestoneId,
			@RequestParam(value = "_cancel", required = false) String cancel,
			@RequestParam(value = "_finish", required = false) String finish,
			@ModelAttribute("milestoneReport") MilestoneReport milestoneReport,
			BindingResult result, SessionStatus status,
			@RequestParam(value = "_page", required = false) int currentPage,
			Model model) {

        Milestone milestone = milestoneService.get_milestone_id(milestoneId);
//        milestoneReport.setBuildResult(true);
        Project project=projectService.fromId(milestone.getProject());
        model.addAttribute("project",project);
        model.addAttribute("milestone",milestone);
        model.addAttribute("milestoneReport",milestoneReport);
        //定义一个map，关联页面号和视图名称
        Map<Integer, String> pageForms = new HashMap<Integer, String>();
        pageForms.put(0, "project/milestone/WizardForm/step1");
        pageForms.put(1, "project/milestone/WizardForm/step2");
        pageForms.put(2, "project/milestone/WizardForm/step3");
        pageForms.put(3, "project/milestone/WizardForm/step4");
        pageForms.put(4, "project/milestone/WizardForm/step5");
        if (StringUtils.isNotEmpty(cancel)) {
            //取消返回到最初页面
            model.addAttribute("result","您选择了取消操作");
            return "project/milestone/WizardForm/result";
        } else if (StringUtils.isNotEmpty(finish)) {
                logger.info("构建里程碑");
                if (!result.hasErrors()) {
                    try{
                      String returnString= postRequestToRDM(milestoneReport);
                        //完成状态用户会话，执行这个函数后，会自动将@SessionAttribute中存储的数据删除
                        if(StringUtils.equals("0000",returnString)){
                            status.setComplete();
                            model.addAttribute("result", "已提交构建给RDM，所有操作都已完成");
                            return "project/milestone/WizardForm/result";
//                            return "project/milestone/list/"+project.getCode();
                        }else{
                            logger.info("构建内容项格式不对，构建失败");
                            milestoneReprterService.delete_tag(milestone,project,milestoneReport.getBuildNote());
                            model.addAttribute("result","提交给RDM时出错，构建内容项格式不对，构建失败");
                            return "project/milestone/WizardForm/result";
                        }

                    }catch (IOException e){
                        e.printStackTrace();
                        logger.info("构建出现异常，构建失败");
                        model.addAttribute("result","构建出现异常，构建失败");
                        return "project/milestone/WizardForm/result";
                    }
                } else {
                    return pageForms.get(currentPage);
                }
        }else {
            //从 _target0-x中取出页面索引号
            int targetPage = WebUtils.getTargetPage(request, "_target", currentPage);
            //判定点击了是上一步还是下一步
            if (targetPage < currentPage) {
                //代表上一步
                return pageForms.get(targetPage);
            }
            //否则就是下一步，需要验证当前页的合法性
                         //           switch (currentPage) {
                        //                case 0:
                        //                    new PeriodicReservationValidator().validateCourt(reservation, result);
                        //                    break;
                        //                case 1:
                        //                    new PeriodicReservationValidator().validateTime(reservation, result);
                        //                    break;
                        //                case 2:
                        //                    new PeriodicReservationValidator().validatePlayer(reservation, result);
                        //                    break;
                         //           }
//            if (!result.hasErrors()) {
                return pageForms.get(targetPage);
//            } else {
//                return pageForms.get(currentPage);
//            }
        }
    }
    /**
     * 提交构建数据到RDM
     *
     * @param milestoneReport  里程碑报告信息
     * @return    RDM的返回编号：0000代表成功，0001代表失败
     * @throws IOException
     */
    public String postRequestToRDM(MilestoneReport milestoneReport) throws IOException {
           String retCode=new String();
        //TODO:待优化 ,可以用遍历的方式进行逐个编码
       String param = URLEncoder.encode("userID", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode("7a6ecf16-1679-46f1-a359-1d5ad0a2ee33", Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("projectName", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getProjectName(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("buildName", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getBuildNote(),Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("productVersion", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getVersion(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("svnUrl", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getSvnAddr(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("buildPurpose", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getGoal(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("componentList", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getComponent(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("devScope", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getDevRange(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("newFeature", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getUpdateFeature(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("deployInfo", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getAttention(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("questionKnown", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getIssueList(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("mailList",Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode(milestoneReport.getEmails(), Prior.DEFAULT_ENCODING);
        param += "&" + URLEncoder.encode("isBG", Prior.DEFAULT_ENCODING) + "=" + URLEncoder.encode("true", Prior.DEFAULT_ENCODING);
     try
        {
            URL realUrl = new URL("http://192.168.75.68/DailyBuildService/DailyBuildService.asmx/BuildNotes");
            //打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "length");
            //设置字符编码
            conn.setRequestProperty("Charset",Prior.DEFAULT_ENCODING);
            // 设置是否向httpUrlConnection输出
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设定请求的方法为"POST"，默认是GET
            conn.setRequestMethod("POST");
            // 连接
             conn.connect();
            DataOutputStream output = new DataOutputStream(conn.getOutputStream());
            output.writeBytes(param);
            output.flush();
            // flush and close
            output.close();
            //这里设置返回数据的编码方式为 utf-8，否则会出现乱码
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),Prior.DEFAULT_ENCODING));
            String line = new String();
            while ((line = reader.readLine()) != null) {
                retCode+=line;
            }
            reader.close();
            conn.disconnect();
            //截取RDM返回字符串的 结果代码。0000代表成功，0001代表失败
            int index_of= retCode.indexOf("<RetCode>");
            retCode=retCode.substring(index_of+9,index_of+13);
            return retCode;
        }catch(Exception e){
            logger.info("发布构建报告时，发送POST请求给RDM出现异常！");
            return "发送POST请求给RDM出现异常！" + e;
        }
    }

    /**
     * 执行后台bat脚本的编译、构建工作
     *
     * @param milestoneId    里程碑id
     * @param releaseVersion   版本
     * @return    构建结果字符串
     */
    @RequestMapping(value = "do_build",method = RequestMethod.POST)
    @ResponseBody
    public String build(int milestoneId, String releaseVersion){
    	String result="";
    	Milestone milestone=milestoneService.get_milestone_id(milestoneId);
        Project project=projectService.fromId(milestone.getProject());
        milestoneReprterService.svn_co_code(milestone,project);
       result=milestoneReprterService.build(releaseVersion,milestone,project);
       if(result!=""){
    	 return result;  
       }
       else{
    	   return "project/milestone/list/".concat(project.getCode());
       }
    }
  
}
